/*
 * srav.cc
 *
 *  Created on: 09/10/2008
 *      Author: pirunga
 */


#include <math.h>
#include <stdio.h>
#include "cv.h"
#include "highgui.h"
#include "srav.h"

void preprocess_threshold(IplImage *src, IplImage *Y, IplImage *Ytmp, IplImage *Cb, IplImage *Cbtmp, IplImage *Cr, IplImage *Crtmp)
{

  cvCvtColor(src,src,CV_RGB2YCrCb);
  cvSplit(src, Y, Cb, Cr, NULL);
  cvSplit(src, Ytmp, Cbtmp, Crtmp, NULL);
}

void skin_threshold(IplImage *src, IplImage *ddst,IplConvKernel *the_elem, IplImage *Y,IplImage *Ytmp,int Ymaxthreshold, int Yminthreshold, IplImage *Cb, IplImage *Cbtmp, int CBmaxthreshold, int CBminthreshold, IplImage *Cr, IplImage *Crtmp, int CRmaxthreshold, int CRminthreshold, int KINDOF, int cols, int rows)
{
  IplImage *dst_mul;
  IplImage *dst_mor;

  CvSize size = cvGetSize(src);

  dst_mul = cvCreateImage(size, 8, 1);
  dst_mor = cvCreateImage(size, 8, 1);

  cvThreshold(Y, Ytmp, Ymaxthreshold, 255, CV_THRESH_TOZERO_INV);
  cvThreshold(Ytmp, Ytmp, Yminthreshold, 255, CV_THRESH_BINARY );
  cvThreshold(Cb, Cbtmp, CBmaxthreshold, 255, CV_THRESH_TOZERO_INV );
  cvThreshold(Cbtmp, Cbtmp, CBminthreshold, 255, CV_THRESH_BINARY );
  cvThreshold(Cr, Crtmp, CRmaxthreshold, 255, CV_THRESH_TOZERO_INV );
  cvThreshold(Crtmp, Crtmp, CRminthreshold, 255, CV_THRESH_BINARY );

  cvMul(Ytmp, Cbtmp, dst_mul);
  cvMul(dst_mul, Crtmp, dst_mul);





  if ( cols == 0 )
    {
      cvSetTrackbarPos("COLS", "CAM",1);
      cols = 1;
    }
  if (rows == 0)
    {
      cvSetTrackbarPos("ROWS", "CAM",1);
      rows = 1;
    }


  // Abertura com linha reta vertical longa
  the_elem = cvCreateStructuringElementEx( 1, rows, 0, rows/2, CV_SHAPE_RECT);
  // horiz
  //the_elem = cvCreateStructuringElementEx( rows, 1, rows/2, 0, CV_SHAPE_RECT);
  cvErode(dst_mul, dst_mor, the_elem);
  cvDilate(dst_mor, dst_mor, the_elem);


  // Fechamento com elemento circular
  the_elem = cvCreateStructuringElementEx( cols, cols, cols/2, cols/2, CV_SHAPE_ELLIPSE); 
  cvDilate(dst_mor, dst_mor, the_elem);
  cvErode(dst_mor, dst_mor, the_elem);
  // Fechamento?... Talvez não seja necessário
  //cvErode(dst_mor, dst_mor, the_elem);
  //cvDilate(dst_mor, dst_mor, the_elem);



  //cvSmooth( dst_mor,dst_mor,CV_GAUSSIAN,3, 0, 0, 0 );

  switch (KINDOF)
    {
    case DST_MUL:
      cvConvertScale(dst_mul, ddst, 1, 0);
      break;
    case DST_MOR:
      cvConvertScale(dst_mor, ddst, 1, 0);
      break;
    }

  cvReleaseImage(&dst_mul);
  cvReleaseImage(&dst_mor);

  cvReleaseStructuringElement(&the_elem);
}

